#!/usr/bin/env python3
"""
数据保存插件测试脚本
测试DataSaver类的各种保存格式和功能
"""

import os
import sys
import json
import tempfile
import shutil

# 添加项目根目录到Python路径
sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'src'))

from plugins.data_analysis.data_analysis import DataSaver

def create_test_data():
    """创建测试数据"""
    return [
        {"id": 1, "name": "张三", "age": 25, "salary": 5000.0},
        {"id": 2, "name": "李四", "age": 30, "salary": 6000.0},
        {"id": 3, "name": "王五", "age": 35, "salary": 7000.0},
        {"id": 4, "name": "赵六", "age": 28, "salary": 5500.0},
        {"id": 5, "name": "孙七", "age": 32, "salary": 6500.0}
    ]

def create_split_test_data():
    """创建拆分数据测试数据"""
    return {
        "split_data": {
            "group1": [
                {"id": 1, "name": "张三", "age": 25},
                {"id": 2, "name": "李四", "age": 30}
            ],
            "group2": [
                {"id": 3, "name": "王五", "age": 35},
                {"id": 4, "name": "赵六", "age": 28}
            ]
        },
        "original_count": 4,
        "split_info": {
            "split_strategy": "field_value",
            "split_field": "department",
            "groups": ["group1", "group2"]
        }
    }

def create_merge_test_data():
    """创建合并数据测试数据"""
    return {
        "merged_data": [
            {"id": 1, "name": "张三", "salary": 5000.0, "department": "IT"},
            {"id": 2, "name": "李四", "salary": 6000.0, "department": "HR"},
            {"id": 3, "name": "王五", "salary": 7000.0, "department": "Finance"}
        ],
        "merge_info": {
            "merge_type": "inner",
            "primary_key": "id",
            "source_count": 2,
            "merged_records": 3
        },
        "merged_by": "id"
    }

def test_json_save():
    """测试JSON格式保存"""
    print("=== 测试JSON格式保存 ===")
    
    # 创建临时目录
    with tempfile.TemporaryDirectory() as temp_dir:
        test_file = os.path.join(temp_dir, "test_data.json")
        
        # 配置插件
        config = {
            "format": "json",
            "output_path": test_file,
            "include_metadata": True,
            "pretty_print": True
        }
        
        saver = DataSaver("test_saver", {"config": config})
        
        # 测试基本数据保存
        test_data = create_test_data()
        result = saver.execute(test_data)
        
        print(f"保存结果: {result}")
        
        # 验证文件是否存在
        if os.path.exists(test_file):
            print(f"文件已创建: {test_file}")
            
            # 读取并验证内容
            with open(test_file, 'r', encoding='utf-8') as f:
                saved_data = json.load(f)
            
            print(f"保存的数据结构: {list(saved_data.keys())}")
            print(f"数据记录数: {len(saved_data.get('data', []))}")
            print("✓ JSON保存测试通过")
        else:
            print("✗ 文件未创建")

def test_csv_save():
    """测试CSV格式保存"""
    print("\n=== 测试CSV格式保存 ===")
    
    with tempfile.TemporaryDirectory() as temp_dir:
        test_file = os.path.join(temp_dir, "test_data.csv")
        
        config = {
            "format": "csv",
            "output_path": test_file
        }
        
        saver = DataSaver("test_saver", {"config": config})
        
        # 测试基本数据保存
        test_data = create_test_data()
        result = saver.execute(test_data)
        
        print(f"保存结果: {result}")
        
        # 验证文件是否存在
        if os.path.exists(test_file):
            print(f"文件已创建: {test_file}")
            
            # 读取并验证内容
            with open(test_file, 'r', encoding='utf-8') as f:
                content = f.read()
            
            print(f"CSV内容预览:\n{content[:200]}...")
            print("✓ CSV保存测试通过")
        else:
            print("✗ 文件未创建")

def test_txt_save():
    """测试TXT格式保存"""
    print("\n=== 测试TXT格式保存 ===")
    
    with tempfile.TemporaryDirectory() as temp_dir:
        test_file = os.path.join(temp_dir, "test_data.txt")
        
        config = {
            "format": "txt",
            "output_path": test_file,
            "pretty_print": True
        }
        
        saver = DataSaver("test_saver", {"config": config})
        
        # 测试基本数据保存
        test_data = create_test_data()
        result = saver.execute(test_data)
        
        print(f"保存结果: {result}")
        
        # 验证文件是否存在
        if os.path.exists(test_file):
            print(f"文件已创建: {test_file}")
            
            # 读取并验证内容
            with open(test_file, 'r', encoding='utf-8') as f:
                content = f.read()
            
            print(f"TXT内容预览:\n{content[:300]}...")
            print("✓ TXT保存测试通过")
        else:
            print("✗ 文件未创建")

def test_split_data_save():
    """测试拆分数据保存"""
    print("\n=== 测试拆分数据保存 ===")
    
    with tempfile.TemporaryDirectory() as temp_dir:
        test_file = os.path.join(temp_dir, "split_data.json")
        
        config = {
            "format": "json",
            "output_path": test_file,
            "include_metadata": True
        }
        
        saver = DataSaver("test_saver", {"config": config})
        
        # 测试拆分数据保存
        split_data = create_split_test_data()
        result = saver.execute(split_data)
        
        print(f"保存结果: {result}")
        
        # 验证文件是否存在
        if os.path.exists(test_file):
            print(f"文件已创建: {test_file}")
            
            # 读取并验证内容
            with open(test_file, 'r', encoding='utf-8') as f:
                saved_data = json.load(f)
            
            print(f"保存的数据包含的组: {list(saved_data.get('data', {}).keys())}")
            print(f"元数据信息: {saved_data.get('metadata', {})}")
            print("✓ 拆分数据保存测试通过")
        else:
            print("✗ 文件未创建")

def test_merge_data_save():
    """测试合并数据保存"""
    print("\n=== 测试合并数据保存 ===")
    
    with tempfile.TemporaryDirectory() as temp_dir:
        test_file = os.path.join(temp_dir, "merged_data.json")
        
        config = {
            "format": "json",
            "output_path": test_file,
            "include_metadata": True
        }
        
        saver = DataSaver("test_saver", {"config": config})
        
        # 测试合并数据保存
        merge_data = create_merge_test_data()
        result = saver.execute(merge_data)
        
        print(f"保存结果: {result}")
        
        # 验证文件是否存在
        if os.path.exists(test_file):
            print(f"文件已创建: {test_file}")
            
            # 读取并验证内容
            with open(test_file, 'r', encoding='utf-8') as f:
                saved_data = json.load(f)
            
            print(f"合并数据记录数: {len(saved_data.get('data', []))}")
            print(f"合并元数据: {saved_data.get('metadata', {})}")
            print("✓ 合并数据保存测试通过")
        else:
            print("✗ 文件未创建")

def test_no_output_path():
    """测试无输出路径（返回数据）"""
    print("\n=== 测试无输出路径（返回数据） ===")
    
    config = {
        "format": "json",
        "include_metadata": True
    }
    
    saver = DataSaver("test_saver", {"config": config})
    
    # 测试数据保存（不指定文件路径）
    test_data = create_test_data()
    result = saver.execute(test_data)
    
    print(f"返回结果: {result}")
    
    if "data" in result:
        print(f"返回数据类型: {type(result['data'])}")
        print(f"返回数据记录数: {len(result['data'].get('data', []))}")
        print("✓ 无输出路径测试通过")
    else:
        print("✗ 未返回数据")

def test_invalid_config():
    """测试无效配置"""
    print("\n=== 测试无效配置 ===")
    
    # 测试无效格式
    config = {
        "format": "invalid_format"
    }
    
    saver = DataSaver("test_saver", {"config": config})
    
    test_data = create_test_data()
    result = saver.execute(test_data)
    
    print(f"无效格式结果: {result}")
    
    if not result.get("saved", True):
        print("✓ 无效配置正确处理")
    else:
        print("✗ 无效配置未正确处理")

def test_config_validation():
    """测试配置验证"""
    print("\n=== 测试配置验证 ===")
    
    # 有效配置
    valid_config = {
        "format": "json",
        "output_path": "/tmp/test.json",
        "include_metadata": True
    }
    
    saver = DataSaver("test_saver", {"config": valid_config})
    is_valid = saver.validate_config()
    
    print(f"有效配置验证结果: {is_valid}")
    
    # 无效配置
    invalid_config = {
        "format": "invalid_format",
        "include_metadata": "not_boolean"  # 应该是布尔值
    }
    
    saver = DataSaver("test_saver", {"config": invalid_config})
    is_valid = saver.validate_config()
    
    print(f"无效配置验证结果: {is_valid}")
    
    if is_valid == False:
        print("✓ 配置验证测试通过")
    else:
        print("✗ 配置验证失败")

if __name__ == "__main__":
    print("开始数据保存插件测试...\n")
    
    try:
        test_json_save()
        test_csv_save()
        test_txt_save()
        test_split_data_save()
        test_merge_data_save()
        test_no_output_path()
        test_invalid_config()
        test_config_validation()
        
        print("\n=== 所有测试完成 ===")
        print("✓ DataSaver插件功能正常")
        
    except Exception as e:
        print(f"\n✗ 测试过程中出现错误: {e}")
        import traceback
        traceback.print_exc()